﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Halk.Spider.Win
{
    public partial class FrmTest : Form
    {
        public FrmTest()
        {
            InitializeComponent();
            this.btnPublish.Click += btnPublish_Click;
        }

        
        void btnPublish_Click(object sender, EventArgs e)
        {
            #region 新浪微博发布示例
            //string usernamePassword = string.Format("{0}:{1}", txtUsername.Text, txtPassword.Text);

            //string username = "fpc2046@hotmail.com";
            //string password = "fansansan5587227";
            //string usernamePassword = username + ":" + password;

            string usernamePassword = string.Format("{0}:{1}", txtUsername.Text, txtPassword.Text);
            string url = "https://api.weibo.com/2/statuses/update.json";
            //string news_title = "VS2010网剧合集：讲述程序员的爱情故事";
            //int news_id = 62747;
            //string t_news = string.Format("{0}，http://news.cnblogs.com/n/{1}/", news_title, news_id);
            string data = "source="+txtAppkey.Text+"&status=" + System.Web.HttpUtility.UrlEncode(txtContent.Text);

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
            System.Net.HttpWebRequest httpRequest = webRequest as System.Net.HttpWebRequest;

            System.Net.CredentialCache myCache = new System.Net.CredentialCache();
            myCache.Add(new Uri(url), "Basic", new System.Net.NetworkCredential(txtUsername.Text, txtPassword.Text));
            httpRequest.Credentials = myCache;
            httpRequest.Headers.Add("Authorization", "Basic " +
            Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(usernamePassword)));

            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            System.Text.Encoding encoding = System.Text.Encoding.ASCII;
            byte[] bytesToPost = encoding.GetBytes(data);
            httpRequest.ContentLength = bytesToPost.Length;
            System.IO.Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytesToPost, 0, bytesToPost.Length);
            requestStream.Close();

            System.Net.WebResponse wr = httpRequest.GetResponse();
            System.IO.Stream receiveStream = wr.GetResponseStream();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8))
            {
                string responseContent = reader.ReadToEnd();
            }
            #endregion
        }
    }
}
